package com.hans.scala

import java.io.{PrintWriter, File}
import java.util.Date

/**
 * User: ZhangJuntao
 * Date: 2014/3/23
 * Time: 18:13
 */
object NewControlStructureExample {
  def main(args: Array[String]) {
    def twice(op: Double => Double, x: Double): Double = op(op(x))
    println(twice(x => x + 1, 5))
    println(twice(_ + 1, 5))

    //代理模式==>贷出模式
    def withPrintWriter1(file: File, op: PrintWriter => Unit) {
      val writer = new PrintWriter(file)
      try {
        op(writer)
      } finally {
        writer.close()
      }
    }
    def withPrintWriter2(file: File)(str: String)(op: (PrintWriter, String) => Unit) {
      val writer = new PrintWriter(file)
      try {
        op(writer, str)
      } finally {
        writer.close()
      }
    }
    withPrintWriter1(
      new File("data\\date1.txt"),
      writer => {
        writer.println(new Date())  //叫名参数
      }
    )
    val file = new File("data\\date2.txt")
    withPrintWriter2(file)("hello world") {
      (writer, str) =>
        writer.println(new Date())
        writer.println(str)
    }
  }
}
